package com.bysj.lms.controller;

import com.bysj.lms.common.Const;
import com.bysj.lms.common.ResultModel;
import com.bysj.lms.pojo.vo.LoginVo;
import com.bysj.lms.pojo.vo.UserVo;
import com.bysj.lms.service.ILoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Api(tags = "登录")
@RestController
public class LoginController {
    public final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    ILoginService loginService;

    @ApiOperation(value = "登录")
    @GetMapping("/login")
    public ResultModel login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        logger.info("账号时是否登录：" + subject.isAuthenticated());
        UserVo loginInfo = null;
        //判断用户是否登陆
        if(!subject.isAuthenticated()){

            try{
                loginInfo = loginService.login(loginVo, response);
                //认证通过
                response.setHeader("Access-Control-Expose-Headers", Const.TOKEN_HEADER_NAME);
            }catch (UnknownAccountException | IncorrectCredentialsException e) {
                return ResultModel.error("账号或密码错误！");
            }catch (Exception e){
                e.printStackTrace();
                return ResultModel.error("系统错误");
            }
        }
        return ResultModel.success("登录成功",loginInfo);
    }
}
